import codecs
import glob
import json
import os
import re
import shutil
import sys

from config import traverse_and_parse_paths
from zip import zip_by_level
from unzip import smart_recursive_unzip
from nested import flatten_to_nested_directories
from merge import merge_directories



# 可以进一步处理解析结果
def zip_by_configs(results):
    """处理解析后的结果"""
    for name, app_config in results.items():
        if not app_config["enabled"]:
            continue
        print(f"打包 {name}...")
        # app_config = results[k]
        output_path = os.path.join(output_base_path, app_config["type"], app_config["app"])
        for path in app_config["path_list"]:
            print(f"处理路径 {path['path']}...")
            # if "parsed_configs" in path and "zip_level" in path["parsed_configs"]:
            #     zip_level = path["parsed_configs"]["zip_level"][0]
            # else:
            #     zip_level = 0
            # if "parsed_configs" in path and "action" in path["parsed_configs"]:
            #     action = path["parsed_configs"]["action"][0]
            # else:
            #     action = None
            # if "parsed_configs" in path and "exclusion_paths" in path["parsed_configs"]:
            #     exclusion_path_list = path["parsed_configs"]["exclusion_paths"][0].split(",")
            # else:
            #     exclusion_path_list = None

            zip_by_level(output_path, path["path"], path["level"], path["action"], path["path_filters"]) # zip到XXX_temp文件夹

        # output_path = os.path.join(output_base_path, app_config["app"])  # 指定正式zip后的文件夹，这个文件夹是经过处理的正式路径文件夹
        # flatten_to_nested_directories(output_temp_path, output_path)
        # shutil.rmtree(output_temp_path)  # 删除XXX_temp文件夹

# def correct_path(wrong_path):
#     # 匹配以反斜杠后跟字母开头的路径（例如 "\C\Users..."）
#     match = re.match(r'^\\([A-Za-z])(\\.*)?', wrong_path)
#     if match:
#         drive_letter = match.group(1)  # 提取驱动器字母（如 "C"）
#         rest_of_path = match.group(2) if match.group(2) else ''  # 剩余部分
#         corrected = f"{drive_letter}:{rest_of_path}"
#         return corrected
#     else:
#         return wrong_path  # 如果不是预期格式，原样返回（可能需后续处理）


def unzip_by_configs(results):
    for name, app_config in results.items():
        print(f"解包 {name}...")
        source_path = os.path.join(output_base_path, app_config["app"])
        drop_path = os.path.join(output_base_path, app_config["app"] + "_drop")
        # extract_directory = r"E:\projects_collector\appstate\pip_unzip"  # 解压目标目录
        smart_recursive_unzip(source_path, drop_path)
    pass

def distribute_by_configs(results):
    for name, app_config in results.items():
        print(f"分发 {name}...")
        drop_path = os.path.join(output_base_path, app_config["app"] + "_drop")

        distribution_dirs = os.listdir(drop_path)  # 获取根目录，一般为C、D这种盘符
        if len(distribution_dirs) > 0:
            for driver in distribution_dirs:
                starting_paths = os.listdir(os.path.join(drop_path, driver))  # 再找一下该盘符下的文件
                for starting_path in starting_paths:
                    src_path = os.path.join(drop_path, driver, starting_path)
                    if sys.platform.startswith('win'):
                        dest_path = os.path.join(f"{driver}:/", starting_path)  # 如果是windows，要转换为盘符
                    else:
                        dest_path = driver  # 如果是linux，那么直接就是/mnt...
                    print(f"move from {src_path} -> {dest_path}")
                    merge_directories(src_path, dest_path)
                    # shutil.move(src_path, dest_path)
        else:
            print(f"没有找到待分发路径")


if __name__ == "__main__":

    app_state_path_list = [
        # {"app": "ZvP Replant", "ver": "fitgirl", "type": "game_save", "path_list":
        #     [
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\PopCap Games\PvZ Replanted", "configs": "zip_level=0", "desc": ""},
        #         {"path": r"C:\Users\JimmyMo\AppData\LocalLow\PopCap Games\PvZ Replanted", "configs": "zip_level=0", "desc": ""},
        #     ]},
        # {"app": "npm", "ver": "", "type": "dev_package", "path_list":
        #     [
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\npm-cache", "configs": "zip_level=1", "desc": ""},
        #         {"path": r"C:\Users\JimmyMo\AppData\Roaming\npm", "configs": "zip_level=1;exclusion_paths=node_modules", "desc": ""},
        #         {"path": r"C:\Users\JimmyMo\AppData\Roaming\npm\node_modules", "configs": "zip_level=1", "desc": ""},
        #         {"path": r"C:\Users\JimmyMo\AppData\Roaming\npm-cache", "configs": "zip_level=1", "desc": ""},
        #     ]},
        # {"app": "pnpm", "ver": "", "type": "dev_package", "path_list":
        #     [
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\pnpm", "configs": "zip_level=0", "desc": ""},
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\pnpm-cache", "configs": "zip_level=0", "desc": ""},
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\pnpm-state", "configs": "zip_level=0", "desc": ""},
        #     ]},
        # {"app": "pip", "ver": "", "type": "dev_package", "path_list":
        #     [
        #         # {"path": r"C:\Users\JimmyMo\AppData\Local\pip", "configs": "zip_level[@http-v2]=1", "desc": "缓存"},
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\pip", "configs": "zip_level=2;exclusion_paths=http-v2,http", "desc": "缓存"},
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\pip\cache\http", "configs": "zip_level=1", "desc": "缓存"},
        #         {"path": r"C:\Users\JimmyMo\AppData\Local\pip\cache\http-v2", "configs": "zip_level=1", "desc": "缓存"},
        #         {"path": r"C:\Users\JimmyMo\pip", "configs": "", "desc": "配置"},
        #     ]}
    ]
    appstate_config_file_list = glob.glob("configs/appstate_projects.json")
    # appstate_config_file_list = glob.glob("configs/appstate_games.json")
    # appstate_config_file_list = glob.glob("configs/appstate_dev.json")
    for appstate_config_file in appstate_config_file_list:
        with codecs.open(appstate_config_file, mode='r', encoding='utf-8') as f:
            temp_json_list = json.load(f)
            for temp_json_item in temp_json_list:
                temp_json_item["enabled"] = (temp_json_item["enabled"] == "true" or temp_json_item["enabled"] == "True")
            app_state_path_list.extend(temp_json_list)
    print(f"app_state_path_list count: {len(app_state_path_list)}")

    # output_base_path = r"E:\projects_collector"
    output_base_path = r"E:\projects_collector\appstate"

    # 执行遍历和解析
    print("开始遍历和解析路径配置...")
    print("=" * 60)
    parsed_results = traverse_and_parse_paths(app_state_path_list, "kp-slash")
    print("=" * 60)
    print("解析完成！")

    # 显示统计信息
    print(f"\n统计信息:")
    print(f"总共处理了 {len(parsed_results)} 个路径")
    print(f"涉及 {len(app_state_path_list)} 个应用")

    zip_by_configs(parsed_results)
    # unzip_by_configs(parsed_results)
    # distribute_by_configs(parsed_results)

